package twitter;
import java.net.URL;

import org.w3c.dom.NodeList;

public class FollowersFetcher {
	Client client;
	
	/**
	 * Fetch the followerslist of current User
	 * @param client Client to pass results to
	 */
	public FollowersFetcher(Client client) {
		this.client = client;
	}
	
	public String fetch() {
		URL url = client.getFollowersURL();
		Downloader downloader = new Downloader(url);
		String xml = downloader.fetchAsString();
		if(xml != null && xml.endsWith("_blocked")) {
			client.clientWasBlocked();
			return "blocked";
		}
		else if(xml != null && xml.endsWith("_protected")) {
			return "protected";
		}
		else if(xml != null && !xml.startsWith("_exeption")) {
			String followers = parse(xml);
			client.handleFollowerResults(followers);
			return "exception";
		}
		else {
			client.handleFollowerResults("");
		}
		return null;
	}

	private String parse(String string) {
		if(string == null) {
			System.out.println(" + Fetched followers (0)");
			return "";
		}
		
		NodeList ids = Helper.parseXMLWithXPath(string, "//id/text()");
		if(ids == null) {
			return "";
		}
		
		String results = "";
		for(int i = 0; i < ids.getLength(); i++) {
			results += ids.item(i).getTextContent() + ",";
		}
		
		System.out.println(" + Fetched followers ("+ ids.getLength() +")");
		
		return results;
	}
}
